'use strict';

const { Service } = require('egg');
const { Op } = require('sequelize');
const ModelName = 'Order'
const { v4: uuidv4 } = require('uuid');

function createOrderNumber() {
  // 获取当前日期和时间
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1; // getMonth() 是从0开始的，所以需要+1
  let day = date.getDate();
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();

  // 格式化日期和时间
  month = month < 10 ? '0' + month : month; // 如果月份小于10，前面添加一个0
  day = day < 10 ? '0' + day : day; // 如果日期小于10，前面添加一个0
  hours = hours < 10 ? '0' + hours : hours; // 如果小时小于10，前面添加一个0
  minutes = minutes < 10 ? '0' + minutes : minutes; // 如果分钟小于10，前面添加一个0
  seconds = seconds < 10 ? '0' + seconds : seconds; // 如果秒数小于10，前面添加一个0

  // 创建订单号
  return year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds;
}
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        { model: this.ctx.model.OrderDetail},
      ]
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
          { model: this.ctx.model.OrderDetail},
      ]
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
      include: [
        { model: this.ctx.model.OrderDetail },
      ]
    });
  }
  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    if (!data.member_id) {
        throw new Error('用户不存在')
    }
    const goodsIds = data.goods.map(el => el.goods_id)
    const findGoodList = await this.app.model.Goods.findAll({
      where: {
        id: {
          [Op.in]: goodsIds
        }
      }
    })
    for (let i = 0; i < data.goods; i++) {
      const good = data.goods[i]
      const count = good.count
      const spec_check = good.spec_check
      for (let j = 0; j < findGoodList.length; j++) {
        const findGood = findGoodList[j]
        if (findGood.id === good.goods_id) {
          const findSpec = JSON.parse(findGood.spec)
          for (let k = 0; k < spec_check.length; k++) {
            const spec_checkItem = spec_check[k]
            const specPName = spec_checkItem.pname
            const specName = spec_checkItem.name
            // 先在 findSpec 中找到 name 为specPName的规格 然后在children中找到name为specName的规格 并去减去他的库存
            const findSpecP = findSpec.find(el => el.name === specPName)
            if (findSpecP) {
                const findSpecC = findSpecP.children.find(el => el.name === specName)
                if (findSpecC) {
                    if (findSpecC.stock < count) {
                    throw new Error('库存不足')
                    }
                    findSpecC.stock -= count
                  console.log('findSpecC.stock',findSpecC.stock)
                    await this.ctx.model.Goods.update({
                      spec: JSON.stringify(findSpec)
                    }, {
                        where: {
                            id: good.goods_id
                        }
                    })
                }
            }
          }
        }
      }
    }
    const order_no = createOrderNumber()
    const orderValue = {
      order_no,
      ...data
    }
    delete orderValue.goods
    // 库存充足
    const insertOrder = await this.ctx.model[ModelName].create({
      ...orderValue
    })
    // 插入明细表
    await this.app.model.OrderDetail.bulkCreate(data.goods.map(el => {
      return {
        order_id: insertOrder.id,
        ...el,
        spec_check: JSON.stringify(el.spec_check)
      }
    }))
    return insertOrder
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }

  async staffAccept(data) {
    if (!data.staff_id) {
        throw new Error('用户不存在')
    }
    const order = await this.ctx.model[ModelName].findOne({
      where: {
        id: data.id
      }
    })
    if (!order) {
      throw new Error('订单不存在')
    }
    if (order.status !== 2) {
      throw new Error('订单状态不正确')
    }
    await this.ctx.model[ModelName].update({
      staff_id: data.staff_id,
      status: 3,
      accept_time: new Date()
    }, {
      where: {
        id: data.id
      }
    })
    return true
  }
  async confirmOrder(data) {
    if (!data.staff_id) {
      throw new Error('骑手不存在')
    }
    // 更新骑手余额
    const staff = await this.ctx.model.Staff.findOne({
      where: {
        id: data.staff_id
      }
    })
    if (!staff) {
      throw new Error('骑手不存在')
    }
    const order = await this.ctx.model[ModelName].findOne({
      where: {
        id: data.id
      }
    })
    if (!order) {
      throw new Error('订单不存在')
    }
    await this.ctx.model[ModelName].update({
      staff_id: data.staff_id,
      status: 4,
      staff_remark: data.staff_remark,
      files: data.fileList.join(','),
      // 到达时间
      confirm_time: new Date()
    }, {
      where: {
        id: data.id
      }
    })
    // config
    const config = await this.ctx.model.Config.findOne({
      where: {
        code: 'order_fee',
        status: 1
      }
    })
    let order_fee = 0

    if (config) {
        order_fee = parseFloat(config.value)
    }
    if (isNaN(order_fee)) {
        order_fee = 0
    }
    let amount = (order_fee * (order.count || 1))
    // 更新骑手余额
    await this.ctx.model.Staff.update({
      balance: parseFloat(staff.balance) + amount,
        total_balance: parseFloat(staff.total_balance) + amount
    }, {
      where: {
        id: data.staff_id
      }
    })
    // 创建一条记录
    await this.ctx.model.StaffBalance.create({
      staff_id: data.staff_id,
      order_id: data.id,
      amount,
      type: 1,
      desc: `订单收入${amount}元，订单号：${order.order_no}，共${order.count || 1}件商品，每件商品收益${order_fee}元`
    })
    return true
  }
}

module.exports = RouterService;
